<template>
  <div class="risk-assessment-template-create">
    <card :isCustomHeader="true">
      <template #header>
        <create-header
          :currentPageStatus.sync="currentPageStatus"
          :breadCrumbTitle="breadCrumbTitle"
          @saveHandle="saveHandle"
          @releaseHandle="releaseHandle"
          @backHandle="backHandle"
        />
      </template>
      <t-row v-if="currentPageStatus === PAGE_STATUS.WELCOME" justify="center">
        <t-form ref="form" :data="surveyData" :rules="FORM_RULES" label-align="top">
          <t-space direction="vertical">
            <t-form-item label="模板名称" name="name">
              <t-input v-model="surveyData.name" placeholder="请输入模板名称" />
            </t-form-item>
            <t-form-item label="关联标签" name="label">
              <t-select
                v-model="surveyData.label"
                creatable
                filterable
                multiple
                placeholder="请选择风险类型"
                :options="[]"
              />
              <!-- <t-tagInput v-model="surveyData.label" :tag-props="{ theme: 'primary', variant: 'light' }" /> -->
            </t-form-item>
            <t-form-item label="模板权限" name="openLevel" v-if="userInfo && userInfo.roleId === 1">
              <t-radio-group v-model="surveyData.openLevel" :options="openLevelOptions" />
            </t-form-item>
            <t-form-item label="简介" name="description">
              <t-input v-model="surveyData.description" placeholder="请输入模板简介内容..." />
            </t-form-item>
            <t-form-item label="欢迎语" name="welcomeMessage" style="margin-bottom: 10px">
              <span class="welcomeMessage-tip">欢迎语将显示在问卷最上方，便于填写人了解更多背景和提示信息</span>
              <tinymce v-model="surveyData.welcomeMessage" />
            </t-form-item>
          </t-space>
        </t-form>
      </t-row>
      <survey-creator
        ref="survey"
        v-show="currentPageStatus === PAGE_STATUS.QUESTION"
        v-model="surveyData.question"
        :risk="riskData"
      />
    </card>
  </div>
</template>

<script>
import Card from '@/components/Card/index.vue';
import Tinymce from '@/components/Tinymce/index.vue';
import SurveyCreator from '@/components/SurveyCreator/index.vue';
import CreateHeader from './components/CreateHeader.vue';

import { mapState } from 'vuex';
import { PAGE_STATUS, openLevelOptions } from '@/constants/risk-assessment-template';
import { addQsTemplate, saveQsTemplate, queryQsTemplate, editQsTemplate } from '@/service/risk-assessment/template';
import { MessagePlugin } from 'tdesign-vue';
import { surveyJsonAddRisk, surveyJsonTakeOutRisk } from './utils/common';

export default {
  name: 'riskAssessmentTemplateCreate',
  components: { Card, Tinymce, CreateHeader, SurveyCreator },
  data() {
    return {
      // 页面状态 填写欢迎语页面WELCOME: 1,创建问题页面QUESTION: 2
      PAGE_STATUS,
      // 开放等级配置  0: 仅供企业内部使用,1: 开放共享（英斯盾平台上企业均可使用）
      openLevelOptions,
      // 当前页面状态
      currentPageStatus: PAGE_STATUS.WELCOME,
      // 面包屑标题
      breadCrumbTitle: '新建模板',
      // 模板数据
      surveyData: {
        name: '',
        label: [],
        openLevel: 0,
        description: '',
        welcomeMessage: '<h4>开始回答您的问卷......</h4>',
        question: '{"widthMode": "responsive"}',
      },
      // 所有风险的数据
      riskData: {},
    };
  },
  computed: {
    ...mapState('user', ['userInfo']),
    // 表单校验规则
    FORM_RULES() {
      return {
        name: [{ required: true, message: '请输入模板名称', type: 'error' }],
        openLevel: [{ required: true, message: '请选择模板权限', type: 'error' }],
        welcomeMessage: [
          { required: true, message: '请输入欢迎语', type: 'error' },
          {
            validator: () => this.surveyData.welcomeMessage.length <= 2048,
            message: '超过最大可输入字符数',
            type: 'error',
          },
        ],
      };
    },
  },
  created() {
    // 编辑时存在id请求数据并填充
    const { id } = this.$route.query;
    if (!id) return;

    this.currentPageStatus = PAGE_STATUS.QUESTION;
    queryQsTemplate(id).then((res) => {
      if (!res || res.isError) return;
      const { question, riskObj } = surveyJsonTakeOutRisk(res.question);
      res.question = question ?? '{"widthMode": "responsive"}';
      res.label = res.label ? res.label.split(',') : [];
      this.riskData = riskObj ?? {};
      this.breadCrumbTitle = res.name ?? '模板';
      this.surveyData = res;
      this.$refs.survey.changeSurveyText(res.question);
    });
  },
  methods: {
    // 保存操作
    saveHandle() {
      if (this.currentPageStatus === PAGE_STATUS.WELCOME) {
        this.$refs.form.validate().then((res) => {
          if (res === true) {
            this.currentPageStatus = PAGE_STATUS.QUESTION;
          }
        });
      }
      if (this.currentPageStatus === PAGE_STATUS.QUESTION) {
        const requestFn = this.surveyData.id ? saveQsTemplate : addQsTemplate;
        requestFn({
          ...this.surveyData,
          label: this.surveyData.label.join(','),
          question: surveyJsonAddRisk(this.surveyData.question, this.riskData),
        }).then((res) => {
          if (!res || res.isError) return;
          MessagePlugin.success('保存模板成功');
        });
      }
    },
    // 发布操作
    releaseHandle() {
      editQsTemplate({
        ...this.surveyData,
        label: this.surveyData.label.join(','),
        question: surveyJsonAddRisk(this.surveyData.question, this.riskData),
      }).then((res) => {
        if (!res || res.isError) return;
        MessagePlugin.success('发布模板成功');
        this.$router.replace('/risk-assessment/template');
      });
    },
    // 返回上一步
    backHandle() {
      this.currentPageStatus = PAGE_STATUS.WELCOME;
    },
  },
};
</script>

<style lang="less" scoped>
.t-form-item__welcomeMessage {
  position: relative;
  .welcomeMessage-tip {
    position: absolute;
    top: -32px;
    right: 0;
    line-height: 32px;
    font-size: 12px;
    color: #777;
  }
}
</style>
